<?php

namespace app\modules\Agreement\controllers;

use Yii;
use app\modules\Agreement\models\Agreement;
use app\modules\Agreement\models\AgreementSearch;
use app\modules\Agreement\models\Goods;
use app\modules\Agreement\models\Model;
use yii\widgets\ActiveForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * AgreementController implements the CRUD actions for Agreement model.
 */
class AgreementController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Agreement models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AgreementSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        //获取所有客户
        $customer = [];
        $customer_model = Agreement::find()->all();
        if($customer_model){
            foreach($customer_model as $cm){
                $customer[$cm->customer_id] = $cm->customer->name;
            }
        }   
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'customer' => $customer,
        ]);
    }

    /**
     * Displays a single Agreement model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Agreement model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Agreement();

        $goods = [new Goods()];

        if ($model->load(Yii::$app->request->post())) {


            if($model->type == 2){
                $t = 'FC';
            }else{
                $t = 'RC';
            }
            $d = date("Y");
            $count = Agreement::find()->count();
            $num = sprintf("%05d", $count+1);
            $model->con_num = $count+1;
            $model->code = sprintf("%s%s%s", $t, $d, $num);

            $goods = Model::createMultiple(Goods::classname());
            Model::loadMultiple($goods, Yii::$app->request->post());
            
            if (Yii::$app->request->isAjax) {  
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 
                return ArrayHelper::merge(
                    ActiveForm::validateMultiple($goods),
                    ActiveForm::validate($model)
                ); 
            }  

            $valid = $model->validate();
            $valid = Model::loadMultiple($goods, Yii::$app->request->post()) && Model::validateMultiple($goods);
                
            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
        
                   if($flag = $model->save(false)){
                        foreach ($goods as $rp) {
                            $rp->agreement_id = $model->id;
                            if (! ($flag = $rp->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }    

                   }
                   if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view','id'=>$model->id]);
                    }

                } catch (Exception $e) {
                    $transaction->rollBack();
                    echo '错误';
                }   
            }
            
        }else{

            $model->status = 1;
            $model->type = 1;
            $model->order_type = 1;

            return $this->render('create', [
                'model' => $model,
                'goods' => $goods
            ]);
        }
    }

    /**
     * Updates an existing Agreement model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $goods = $model->goods;

        if ($model->load(Yii::$app->request->post())) {

            if($model->type == 2){
                $t = 'FC';
            }else{
                $t = 'RC';
            }
            $d = date("Y");
            $num = sprintf("%05d", $model->con_num);
            $model->code = sprintf("%s%s%s", $t, $d, $num);

            $oldIDs = ArrayHelper::map($goods, 'id', 'id');
            $goods = Model::createMultiple(Goods::classname(),$goods);
            Model::loadMultiple($goods, Yii::$app->request->post());

            if (Yii::$app->request->isAjax) {  
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 
                return ArrayHelper::merge(
                    ActiveForm::validateMultiple($goods),
                    ActiveForm::validate($model)
                ); 
            } 
            
            $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($goods, 'id', 'id')));
            
            $valid = $model->validate();
            $valid = Model::validateMultiple($goods) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
            
                   if($flag = $model->save(false)){
                        if (! empty($deletedIDs)) {
                            Goods::deleteAll(['id' => $deletedIDs]);
                        }
                        foreach ($goods as $rp) {
                            $rp->agreement_id = $model->id;
                            if (! ($flag = $rp->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }    

                   }
                   if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view','id'=>$model->id]);
                    }

                } catch (Exception $e) {
                    $transaction->rollBack();
                    echo '错误';
                }   
            }

        }else{
            return $this->render('update', [
                'model' => $model,
                'goods' => $goods
            ]);
        }

       
    }

    /**
     * Deletes an existing Agreement model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Agreement model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Agreement the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Agreement::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
